package com.hulytu.android.hijack;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Build;

import java.io.ByteArrayInputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
 * @author Chris (hulytu@163.com)
 * @date 2021/11/23
 */
public final class Utils {

    public static int getSignInfoHashCode(Context context) {
        Signature signature = getSignature0(context);
        return signature == null ? 0 : signature.hashCode();
    }

    public static String getSignInfoNew(Context context) {
        Signature signature = getSignature0(context);
        return signature == null ? null : parseSignature(signature.toByteArray());
    }

    private static Signature getSignature0(Context context) {
        Signature[] signatures = getSignatures(context);
        return signatures == null || signatures.length == 0 ? null : signatures[0];
    }

    @SuppressLint("PackageManagerGetSignatures")
    private static Signature[] getSignatures(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            Signature[] signatures;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                PackageInfo packageInfo = manager.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
                signatures = packageInfo.signatures;
            } else {
                PackageInfo packageInfo = manager.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNING_CERTIFICATES);
                signatures = packageInfo.signingInfo.getApkContentsSigners();
            }
            return signatures;
        } catch (Exception ignored) {
        }
        return null;
    }


    private static String parseSignature(byte[] signature) {
        try {

            CertificateFactory factory = CertificateFactory.getInstance("X.509");

            String pubKey = factory.generateCertificate(new ByteArrayInputStream(signature))
                    .getPublicKey()
                    .toString();
            return pubKey.substring(pubKey.indexOf("modulus") + 8, pubKey.indexOf("publicExponent") - 1);

        } catch (CertificateException e) {
            return null;
        }
    }

}
